package com.util;

import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.mapping;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Stream;

public class MapUtil {

	/**map的value转换为List
	 * @param list
	 * @return
	 */
	public static <K, V> List<V> mapValuesToList(Map<K, V> map){
		if(map == null){
			return null;
		}
		return map.values().stream().collect(toList());
	}

	/**map的value转换为List
	 * @param list
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <K, V, Y> List<Y> mapValuesToList2(Map<K, V> map, Class<Y> y){
		if(map == null){
			return null;
		}
		return map.values().stream().map(v -> (Y)v).collect(toList());
	}

	public static <K, V> Map<K, V> streamToMap(Stream<V> stream, Function<? super V, ? extends K> keyMapper, Function<? super V, ? extends V> valueMapper){
		if(stream != null){
			return stream.collect(toMap(keyMapper, valueMapper));
		}
		return null;
	}

	public static <K, V> Map<K, V> listToMap(List<V> list, Function<? super V, ? extends K> keyMapper, Function<? super V, ? extends V> valueMapper){
		if(list != null && list.size() > 0){
			return list.stream().collect(toMap(keyMapper, valueMapper));
		}
		return null;
	}

	public static <K, V> Map<K, List<V>> listToMapList(List<V> list, Function<? super V, ? extends K> keyMapper){
		if(list != null && list.size() > 0){
			return streamToMapList(list.stream(), keyMapper);
		}
		return null;
	}

	public static <K, V, T> Map<K, List<T>> listToMapList(List<V> list, Function<? super V, ? extends K> keyMapper, Function<? super V, ? extends T> valueMapper){
		if(list != null && list.size() > 0){
			return streamToMapList(list.stream(), keyMapper, valueMapper);
		}
		return null;
	}

	public static <K, V> Map<K, List<V>> streamToMapList(Stream<V> stream, Function<? super V, ? extends K> keyMapper){
		if(stream != null){
			return stream.collect(groupingBy(keyMapper));
		}
		return null;
	}

	public static <K, V, T> Map<K, List<T>> streamToMapList(Stream<V> stream, Function<? super V, ? extends K> keyMapper, Function<? super V, ? extends T> valueMapper){
		if(stream != null){
			return stream.collect(groupingBy(keyMapper, mapping(valueMapper, toList())));
		}
		return null;
	}

}
